<?php

/**
 * 特批授权仓库
 * @author yuzy 2015-5-13
 */

namespace common\repositories\myhtsq;

use common\repositories\BaseRepository;
use common\repositories\common\MyscrmOrganizationRepository;
use common\support\StringHelper;
use common\support\Helper;
use common\entities\myhtsq\SpecialApprovalAuthorizeEntity;
use common\error\ErrorCode;
use Exception;

class SpecialApprovalAuthorizeRepository extends BaseRepository {

    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 特批授权列表
     * @param \common\support\PageParam $pageParam 分页参数
     * @param integer $areaId 区域id
     * @param string $fulfil 
     * @param string $keyword 关键字
     * @return array
     */
    public static function getSpecialApprovalAuthorizeList($pageParam, $areaId, $fulfil, $keyword) {
        $skip = $pageParam->getSkipByPageParam();
        $query = SpecialApprovalAuthorizeEntity::find();
        $query->select("myscrm_special_approval_authorize.*,"
                . "myscrm_contract_manage.customer_name,myscrm_contract_manage.contract_id,myscrm_contract_manage.area_id");
        //区域id
        if (!empty($areaId)) {
            $query->andWhere(['myscrm_contract_manage.area_id' => $areaId]);
        }

        // 是否兑现
        if (!empty($fulfil)) {
            if($fulfil == '1'){
                $query->andWhere('myscrm_special_approval_authorize.actual_fulfil_time is not null');
            }
            else{
                $query->andWhere('myscrm_special_approval_authorize.actual_fulfil_time is null');
            }
        }

        // 关键字过滤
        if (!empty($keyword)) {
            //$query->andWhere(['or', ['like', 'myscrm_contract_manage.contract_code', $keyword], ['like', 'myscrm_organization.UniqueName', $keyword], ['like', 'myscrm_organization.FriendlyName', $keyword]]);
            $query->andWhere(['or', ['like', 'myscrm_contract_manage.contract_code', $keyword]]);

        }

        $query->leftJoin('myscrm_contract_manage', 'myscrm_special_approval_authorize.contract_code = myscrm_contract_manage.contract_code')
                ->offset($skip)
                ->limit($pageParam->pageSize)
                ->orderBy([$pageParam->sortBy => $pageParam->sortAsc]);

        $result = $query->asArray()->all(); //这里必须asArray，否则无法获取关联字段的属性值

        if(!empty($result)){
            foreach($result as $k=>$v){
                $org = MyscrmOrganizationRepository::getById($v["organization_id"]);
                $uniqueName = "";
                $friendlyName = "";
                if (!empty($org)) {
                    $uniqueName = $org->UniqueName;
                    $friendlyName = $org->FriendlyName;
                }
                $result[$k]["UniqueName"] = $uniqueName;
                $result[$k]["FriendlyName"] = $friendlyName;

                $result[$k]["principal_name"] = ErpUserRepository::getUserNameByBuguid($v["promise_fulfil_principle"]);
                $result[$k]["area_name"] = ErpBusinessUnitRepository::getBunameByBuguid($v["area_id"]);
            }
        }
                
        $totalResult = SpecialApprovalAuthorizeEntity::find();
        if (!empty($areaId)) {
            $totalResult->andWhere(['myscrm_contract_manage.area_id' => $areaId]);
        }
        if (!empty($fulfil)) {
            if($fulfil == '1'){
                $totalResult->andWhere('myscrm_special_approval_authorize.actual_fulfil_time is not null');
            }else{
                $totalResult->andWhere('myscrm_special_approval_authorize.actual_fulfil_time is null');
            }
        }
        if (!empty($keyword)) {
            //$totalResult->andWhere(['or', ['like', 'myscrm_contract_manage.contract_code', $keyword], ['like', 'myscrm_organization.UniqueName', $keyword], ['like', 'myscrm_organization.FriendlyName', $keyword]]);
            $totalResult->andWhere(['or', ['like', 'myscrm_contract_manage.contract_code', $keyword]]);

        }   
        $totalResult->leftJoin('myscrm_contract_manage', 'myscrm_special_approval_authorize.contract_code = myscrm_contract_manage.contract_code');
        $total = $totalResult->count();

        $pageResult = Helper::setPageResult($total, $result);
        return $pageResult;
    }

    /**
     * 获取特批授权实体信息
     * @param string $authorizeId
     * @return \common\entities\myhtsq\SpecialApprovalAuthorizeEntity
     */
    public static function getSpecialApprovalAuthorizeInfo($authorizeId)
    {
        $model = SpecialApprovalAuthorizeEntity::find()
            ->select('myscrm_special_approval_authorize.*,')
            ->where(['special_approval_authorize_id' => $authorizeId])
            ->asArray()
            ->one();
        if (!empty($model)) {
            $org = MyscrmOrganizationRepository::getById($model["organization_id"]);
            $uniqueName = "";
            $friendlyName = "";
            if (!empty($org)) {
                $uniqueName = $org->UniqueName;
                $friendlyName = $org->FriendlyName;
            }
            $model["UniqueName"] = $uniqueName;
            $model["FriendlyName"] = $friendlyName;
            $model["principal_name"] = ErpUserRepository::getUserNameByBuguid($model["promise_fulfil_principle"]);
        }

        return $model;
    }

    /**
     * 新增特批授权
     * @param \common\models\myhtsq\SpecialApprovalAuthorizeModel $authorizeModel
     * @return boolean|string 失败返回false，成功返回新增的特批授权Id
     */
    public function addSpecialApprovalAuthorize($authorizeModel) {
        try {
            $entity = new SpecialApprovalAuthorizeEntity();
            $entity->setAttributes($authorizeModel->attributes);
            $entity->special_approval_authorize_id = StringHelper::uuid();
            $result = $entity->save();
            if ($result === FALSE) {
//                $error = $entity->firstErrorMessage;
                return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_AUTHORIZE_SAVE_FAIL);
            } else {
                return $entity->primaryKey;
            }
        } catch (Exception $ex) {
            return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_AUTHORIZE_SAVE_FAIL, (string) $ex);
        }
    }

    /**
     * 更新特批授权
     * @param \common\models\myhtsq\SpecialApprovalAuthorizeModel $authorizeModel
     * @return boolean|string 失败返回false，成功返回编辑的特批授权Id
     */
    public function updateSpecialApprovalAuthorize($authorizeModel) {
        try {
            $entity = SpecialApprovalAuthorizeRepository::getSpecialApprovalAuthorizeById($authorizeModel->special_approval_authorize_id);
            if (is_null($entity)) {
                return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_AUTHORIZE_SAVE_FAIL);
            }
            $entity->setAttributes($authorizeModel->toArray());
            $result = $entity->update();
            if ($result === FALSE) {
//                $error = $entity->firstErrorMessage;
                return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_AUTHORIZE_SAVE_FAIL);
            } else {
                return $entity->special_approval_authorize_id;
            }
        } catch (Exception $ex) {
            return $this->setAndReturn(ErrorCode::ERR_SPECIAL_APPROVAL_INVOICE_SAVE_FAIL, (string) $ex);
        }
    }

    /**
     * 根据Id获取特批授权
     * @param type $authorizeId
     * @return \common\entities\myhtsq\SpecialApprovalAuthorizeEntity
     */
    public static function getSpecialApprovalAuthorizeById($authorizeId) {
        return SpecialApprovalAuthorizeEntity::findOne(['special_approval_authorize_id' => $authorizeId]);
    }

    /**
     * 根据合同编号，获取特批授权对象
     * @param string $contractCode 合同编号
     * @return common\entities\myhtsq\SpecialApprovalAuthorizeEntity
     */
    public static function getSpecialApprovalAuthorizeByContractCode($contractCode) {
        return SpecialApprovalAuthorizeEntity::find()->where(['contract_code' => $contractCode])->one();
    }

}
